//
//  QDStationsTableViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/2/26.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit

/// 线路的collectionViewCell
private final class QDStationsCollectionViewCell: NWCollectionViewCell {

    /// 矩形视图
    let rectView = UIImageView()
    /// 显示线路的标签
    let titleLabel = UILabel()
    /// 选中的颜色
    var selectTextColor = QDColors.theme
    
    override func buildView() {
        super.buildView()
        
        titleLabel.text = "2号线"
        titleLabel.textColor = QDColors.black
        titleLabel.font = Font.light.font(size: 16)
        
        rectView.isHidden = true
        
        contentView.addSubview(rectView)
        contentView.addSubview(titleLabel)
        
        rectView.snp.makeConstraints { (make) in
            make.left.top.bottom.equalToSuperview()
            make.width.equalTo(3)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(28)
            make.height.equalTo(22)
            make.centerY.equalToSuperview()
        }
    }
    
    override var isSelected: Bool {
        willSet {
            contentView.backgroundColor = newValue ? .white : #colorLiteral(red: 0.9490196078, green: 0.9607843137, blue: 0.9529411765, alpha: 1)
            titleLabel.font = newValue ? Font.semibold.font(size: 16) : Font.light.font(size: 16)
            rectView.isHidden = !newValue
            titleLabel.textColor = newValue ? selectTextColor : QDColors.black
        }
    }
}


/// 站点的tableViewCell
final class QDStationsTableViewCell: NWTableViewCell {
    
    /// 显示站点的标签
    let titleLabel = UILabel()
    
    override func buildView() {
        super.buildView()
        
        bottomLineHeight = 0.5
        bottomLineInset = UIEdgeInsets(top: 0, left: 38, bottom: 0, right: 20)
        bottomLineView.backgroundColor = #colorLiteral(red: 0.9294117647, green: 0.9411764706, blue: 0.9333333333, alpha: 1)
            
        titleLabel.font = Font.light.font(size: 16)
        titleLabel.textColor = QDColors.black
        titleLabel.text = "太平角公园(一疗)"
        
        contentView.addSubview(titleLabel)
        
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(40)
            make.top.equalToSuperview().offset(10)
            make.height.equalTo(22)
        }
    }
}


/// 线路以及站点列表控制器
final class QDStationsContainerViewController: NWViewController {

    //// 开放数据
    
    ///选中响应
    weak var selectAction: QDStationsViewSelectAction?
    
    /// 最近的站点
    var nearStation = QDNearMetroStationContainer() {
        willSet {
            recentLabel.text = newValue.stationName
        }
    }
    /// 所有的线路
    var stationLines = [QDMetroLine]() {
        didSet {
            
            if stationLines.count == 0 { return }
            //默认选择第一个
            currentStations = stationLines.first!.stationData
            //左侧进行刷新
            collectionView.reloadData()
            //右侧刷新
            stationsTableView.reloadData()
            
            DispatchQueue.main.async {
                self.collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: .top)
            }
        }
    }
    /// 当前线路的站点
    private var currentStations = [QDMetroStation]()
    
    
    /// 放置最近车站的header
    private let headerView = UIView()
    /// 展示阴影的视图
    private let shadowView = UIImageView()
    /// 最近站点描述: ex: 离我最近
    private let headerDescLabel = UILabel()
    /// 距离最近的站点
    private let recentLabel = RITLExternLabel()
    /// 距离站点最近的背景
    private let recentBackgroundImageView = UIImageView()
    /// 显示路线的布局对象
    private lazy var collectionFlowLayout: UICollectionViewFlowLayout = {
       
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.sectionInset = .zero
        flowLayout.itemSize = CGSize(width: 100, height: 62)
        flowLayout.minimumLineSpacing = .leastNormalMagnitude
        flowLayout.minimumInteritemSpacing = .leastNormalMagnitude
        
        return flowLayout
    }()
    /// 显示线路的collectionView
    private lazy var collectionView: UICollectionView = {
       
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: self.collectionFlowLayout)
        collectionView.dataSource = self
        collectionView.delegate = self
        
        return collectionView
    }()
    /// 记录当前的线路位置
    private var currentIndex = 0
    /// 显示站点的tableView
    private let stationsTableView = UITableView()
    
    
    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
        
        //注册cell
        stationsTableView.register(QDStationsTableViewCell.self, forCellReuseIdentifier: "s_cell")
        collectionView.register(QDStationsCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = .white
        headerView.backgroundColor = .clear
        shadowView.image = nav_shadowImage
        
        headerDescLabel.text = "离我最近"
        headerDescLabel.font = Font.medium.font(size: 14)
        headerDescLabel.textColor = QDColors.black
        
        recentLabel.extensionSpace = 13
        recentLabel.text = "太平角公园(一疗)"
        recentLabel.font = Font.regular.font(size: 14)
        recentLabel.textColor = QDColors.black
        recentLabel.textAlignment = .center
        recentLabel.layer.cornerRadius = 16
        recentLabel.clipsToBounds = true
        
        recentBackgroundImageView.image = "sta_near_background".namedImage?.resizableImage(withCapInsets: UIEdgeInsets(top: 8, left: 18, bottom: 8, right: 18), resizingMode: .stretch)
        //追加点击事件
        recentBackgroundImageView.isUserInteractionEnabled = true
        recentBackgroundImageView.addUIControlHandler {[unowned self] (_) in
            
            if self.nearStation.disable {  self.view.showTextHUD(text: "暂未开通"); return }//不提示
            
            self.selectAction?.stationsViewController(didSelect: self.nearStation.stationName, stationId: self.nearStation.stationId, line: self.nearStation.lineName.components(separatedBy: ","))
        }
        
        view.addSubview(collectionView)
        view.addSubview(stationsTableView)
        view.addSubview(headerView)
        headerView.addSubview(shadowView)
        headerView.addSubview(headerDescLabel)
        headerView.addSubview(recentBackgroundImageView)
        headerView.addSubview(recentLabel)

        collectionView.backgroundColor =  #colorLiteral(red: 0.9490196078, green: 0.9607843137, blue: 0.9529411765, alpha: 1)
        stationsTableView.rowHeight = 44
        stationsTableView.estimatedRowHeight = 0
        stationsTableView.delegate = self
        stationsTableView.dataSource = self
        stationsTableView.separatorStyle = .none
        stationsTableView.tableFooterView = UIView()
        stationsTableView.backgroundColor = .white
        stationsTableView.showsVerticalScrollIndicator = false
        
        headerView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(4)
            make.height.equalTo(52)
        }
        
        headerDescLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(27)
            make.height.equalTo(20)
            make.width.equalTo(56)
            make.bottom.equalToSuperview().inset(22)
        }
        
        recentLabel.snp.makeConstraints { (make) in
            make.left.equalTo(headerDescLabel.snp.right).offset(12)
            make.height.equalTo(32)
            make.centerY.equalTo(headerDescLabel)
        }
        
        recentBackgroundImageView.snp.makeConstraints { (make) in
            make.left.equalTo(headerDescLabel.snp.right).offset(4)
            make.right.equalTo(recentLabel.snp.right).offset(8)
            make.height.equalTo(48)
            make.centerY.equalTo(recentLabel)
        }
        
        shadowView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(5)
            make.bottom.equalToSuperview().inset(0.5)
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.left.bottom.equalToSuperview()
            make.top.equalTo(headerView.snp.bottom).inset(4.5)
            make.width.equalTo(100)
        }
        
        stationsTableView.snp.makeConstraints { (make) in
            make.bottom.right.equalToSuperview()
            make.top.equalTo(collectionView)
            make.left.equalTo(collectionView.snp.right)
        }
    }
}



extension QDStationsContainerViewController: UICollectionViewDataSource,UICollectionViewDelegate {
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return stationLines.count
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        
        if let stationCell = cell as? QDStationsCollectionViewCell {
            
            let stationLine = stationLines[indexPath.item]
            stationCell.selectTextColor = stationLines[indexPath.item].selectColor
            stationCell.rectView.image = stationLines[indexPath.item].rectImage
            stationCell.titleLabel.text = "\(stationLine.lineName)"
        }
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        /// 已经选中相同的不响应
        if currentIndex == indexPath.item { return }
        //记录标志位
        currentIndex = indexPath.item

        //TODO: 切换数据源，刷新tableView
        currentStations = stationLines[indexPath.item].stationData
        stationsTableView.contentOffset = .zero
        stationsTableView.reloadData()
    }
}


extension QDStationsContainerViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return currentStations.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "s_cell", for: indexPath)
        
        if let titleCell = cell as? QDStationsTableViewCell {
            let station = currentStations[indexPath.row]
            //进行数据赋值
            titleCell.titleLabel.text = station.name
            titleCell.titleLabel.textColor = station.disable ? QDColors.gray2 : QDColors.black
        }
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let station = currentStations[indexPath.row]
        if station.disable {
            view.showTextHUD(text: "暂未开通");  return
        }
        
        selectAction?.stationsViewController(didSelect: station.name, stationId: station.id, line: [station.lineName])
    }
}
